#!/bin/bash

function ShowHelp()
{
    echo "使用方法："
    echo "    $1  txt_file  split_num"
    echo " 如："
    echo "    $1  1.txt  5"
}

if [ $# -ne 2 ]; then
    ShowHelp `basename $0`
    exit 1
fi

txt_file=$1
split_num=$2
mulu="mulu.txt"
grep -n -E "第([0-9]+|(一|二|三|四|五|六|七|八|九|零|十|百|千)+)章" $txt_file > $mulu
line_num=`wc -l $mulu | awk '{print $1}'`
average=`expr $line_num / $split_num`

args=""
current=$average
for i in $(seq 2 $split_num) ; do
    pos=`awk -v FS=":" -v curr=$current 'NR==curr {print $1}' $mulu`
    # pos=`sed -n "${current}p" $mulu | awk -v FS=":" '{print $1}'`
    args="$args $pos"
    current=`expr $current + $average`
done

prefix=`basename $txt_file .txt`
suffix="-%02d.txt"
csplit --prefix=$prefix --suffix-format=$suffix  $txt_file  $args
